package mail

import (
	"bytes"
	"crypto/tls"
	"html/template"
	"log"
	"regexp"

	"gopkg.in/gomail.v2"
)

// IsValidEmail 判断邮箱地址是否正确
func IsValidEmail(email string) bool {
	emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
	return emailRegex.MatchString(email)
}

// SendMail 发送邮件
func SendMail(to []string, subject string, body string) error {
	// 邮件发送器
	m := gomail.NewMessage()

	m.SetHeader("From", "bms@shrewdboy.top")
	m.SetHeader("To", to...)
	m.SetHeader("Subject", subject)
	m.SetBody("text/html", body)

	// 发送邮件
	d := gomail.NewDialer("mail.shrewdboy.top", 465, "bms@shrewdboy.top", "SPM-B2-bms")
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	if err := d.DialAndSend(m); err != nil {
		log.Println("failed to send email: ", err)
		return err
	}

	return nil
}

// SendMailWithTemplate 发送HTML模板邮件
func SendMailWithTemplate(to []string, subject string, tmplPath string, data interface{}) error {
	// 解析模板
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		log.Println("failed to parse template: ", err)
		return err
	}

	// 执行模板并渲染
	var tpl bytes.Buffer
	if err = tmpl.Execute(&tpl, data); err != nil {
		log.Println("failed to render template: ", err)
		return err
	}

	// 发送邮件
	return SendMail(to, subject, tpl.String())
}
